package com.smt.take.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.smt.take.R
import com.smt.take.model.beans.OrderBean
import com.smt.take.presenter.OrderFragmentPresenter
import com.smt.take.ui.adapter.OrderRvAdapter
import com.smt.take.utils.TakeOutApp

class OrderFragment : Fragment() {

    private lateinit var rvOrder: RecyclerView
    private lateinit var refreshLayout: SwipeRefreshLayout
    private lateinit var presenter: OrderFragmentPresenter
    private lateinit var adapter: OrderRvAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = View.inflate(activity, R.layout.fragment_order, null)
        presenter = OrderFragmentPresenter(this)
        rvOrder = view.findViewById(R.id.rv_order_list)
        rvOrder.layoutManager = LinearLayoutManager(activity)
        adapter = OrderRvAdapter(context)
        rvOrder.adapter = adapter
        refreshLayout = view.findViewById(R.id.refreshLayout)
        refreshLayout.setOnRefreshListener {
            initData()
        }
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // 访问服务器，获取所有订单数据
        initData()
    }

    private fun initData() {
        val id = TakeOutApp.sUser.id
        if (id == -1) {
            Toast.makeText(context, "请先登录，再查看订单", Toast.LENGTH_SHORT).show()
        } else {
            presenter.getOrderList(id.toString())
        }
    }

    fun onOrderSuccess(data: MutableList<OrderBean>) {
        // 给adapter绑定数据
        adapter.setData(data)
        refreshLayout.isRefreshing = false
    }

    fun onOrderFailed() {
        Toast.makeText(context, "服务器错误", Toast.LENGTH_SHORT).show()
        refreshLayout.isRefreshing = false
    }
}